package jrain.utils.ip;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

import jrain.utils.exception.ServiceException;

/**
 * <pre>
 * 作者：489088214@qq.com 
 * 描述： IP服务
 * </pre>
 */
public class IpUtils {

	private static final String IP = "(2[5][0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})";
	private static final Pattern IP_PATTERN = Pattern.compile(IP);

	/**
	 * 是否IP地址
	 * @param ip IP地址
	 * @return 是否IP地址
	 */
	public static boolean isIp(String ip) {
		return IP_PATTERN.matcher(ip).matches();
	}

	/**
	 * 获取IP地址
	 * @return IP地址集合
	 */
	public static Set<String> getIps() {
		Set<String> rsSet = new HashSet<>();
		try {
			Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
			while (interfaces.hasMoreElements()) {
				NetworkInterface ni = interfaces.nextElement();
				Enumeration<InetAddress> addresss = ni.getInetAddresses();
				while (addresss.hasMoreElements()) {
					InetAddress nextElement = addresss.nextElement();
					String hostAddress = nextElement.getHostAddress();
					rsSet.add(hostAddress);
				}
			}
		} catch (SocketException e) {
			throw new ServiceException(e.getMessage(), e);
		}
		return rsSet;
	}

	/**
	 * 获取IPV4地址集合
	 * @return IPV4地址集合
	 */
	public static Set<String> getIpv4s() {
		Set<String> rsSet = new HashSet<>();
		Set<String> list = getIps();
		for (String ipAddress : list) {
			if (isIp(ipAddress) && !"127.0.0.1".equals(ipAddress)) {
				rsSet.add(ipAddress);
			}
		}
		return rsSet;
	}

}
